<template>
  <view>
    <uni-popup ref="payPopup" type="bottom">
      <view class="popup-pay">
        <view class="popup-content">
          <view class="pay-title">{{ payType }}</view>

          <!--<qui-button size="100%" type="primary" class="pay-btn" @click="publishClick()">
            {{ p.pay }}{{ money }}{{ p.rmb }}
          </qui-button>-->
          <button class="pay-btn" @click="payChoice">
            {{ p.pay }}
            <view class="pay-num">￥{{ money }}</view>
            {{ p.rmb }}
          </button>
          <checkbox-group @change="radioMyHead">
            <label class="pay-radio">
              <view>
                <checkbox :value="checkVal" checked="true" class="radio" color="#2699fb" />
              </view>
              <view class="radio-word" :style="{ color: checkStatus ? '#2699fb' : '#999' }">
                {{ p.showMyHead }}
              </view>
            </label>
          </checkbox-group>
        </view>
        <view class="popup-content-space"></view>
        <text class="popup-cancel-btn" @click="cancel('1')">{{ p.cancel }}</text>
      </view>
    </uni-popup>
    <uni-popup ref="payTypePopup" type="bottom">
      <view class="popup-pay-type">

        <view class="money-box">
          ￥
          <view class="money-num">{{ money }}</view>
        </view>
        <view class="pay-type-chi" v-for="(item, index) in payTypeData" :key="index">

          <radio-group @change="radioChange" class="pay-type-radio-box">
            <block v-if="descriptionShow&&item.value === '0'&& money>balance">
              <label class="pay-type-radio">
                <view class="pay-type-l">
                  <qui-icon :name="item.icon" :color="item.color" class="icon-pay"></qui-icon>
                  <view class="pay-type-word">{{ item.name }}</view>
                </view>
                <view class="pay-type-r">
                  <view class="check-tip" v-if=" money <= walletBalance">
                    {{ p.walletBalance }}，￥{{ walletBalance }}
                  </view>
                  <view class="check-tip" v-else-if=" money > walletBalance">
                    {{ p.walletBalanceNo }}{{ walletBalance }}{{ p.rmb }}
                  </view>

                  <view>

                    <radio :value="item.value" :name="item.index" :checked="index === current" class="radio"
                      color="#2699fb" :disabled="
                       (money >walletBalance)  " />
                  </view>
                </view>
              </label>
            </block>
            <block v-if="descriptionShow &&item.value === '1'&& money<=balance">
              <label class="pay-type-radio">
                <view class="pay-type-l">
                  <qui-icon :name="item.icon" :color="item.color" class="icon-pay"></qui-icon>
                  <view class="pay-type-word">{{ item.name }}</view>
                </view>
                <view class="pay-type-r">
                  <view class="check-tip" v-if="!walletStatus" @click="payStatusClick">
                    {{ p.passwordSetting }}
                  </view>
                  <view class="check-tip" v-else-if="money <= walletBalance">
                    {{ p.walletBalance }}，￥{{ balance }}
                  </view>
                  <view class="check-tip" v-else-if=" money > balance">
                    {{ p.walletBalanceNo }}{{ balance }}{{ p.rmb }}
                  </view>

                  <view>
                    <radio :value="item.value" :name="item.index" :checked="index === current" class="radio"
                      color="#2699fb" :disabled="
                                      (!walletStatus ) ||
                                        (!(money <= balance) ) ||
                                        item.hide
                                    " />
                  </view>
                </view>
              </label>
            </block>

          </radio-group>
        </view>

        <view class="pay-tip" v-if="payTipShow">
          ￥{{ money }}{{ p.rmb }}{{ p.payTo }}{{ toName }}{{ p.ofAccount }}
        </view>
        <!--<qui-button size="max" type="primary" class="paySureBtn" @click="paysureShow">
          {{ p.surePay }}￥{{ money }}{{ p.rmb }}
        </qui-button>-->
        <button v-if="money<=balance || money<=walletBalance" class="paySureBtn" @click="paysureShow">
          {{ p.surePay }}￥{{ money }}{{ p.rmb }}
        </button>
        <button v-else class="paySureBtn" @click="gotoPage('/shoppages/user/my-wallet/my-wallet')">
          去充值 ￥{{ money }}{{ p.rmb }}
        </button>
        <view class="popup-share-content-space"></view>

        <text class="popup-share-btn" @click="cancel('2')">取消</text>
      </view>
    </uni-popup>
    <uni-popup ref="keyboardPopup" type="center">
      <qui-pay-keyboard ref="keyboard" :show="show" :money="money" :password="payPassword" @onInput="onInput"
        @close="close"></qui-pay-keyboard>
    </uni-popup>
  </view>
</template>

<script>
  import {
    mapMutations
  } from 'vuex';
  import user from '@/mixin/user';
  export default {
    mixins: [
      user,
    ],
    props: {
      threadId: {
        type: [String, Number],
        default: '',
      },
      // 钱包设置支付密码状态
      walletStatus: {
        type: Boolean,
        default: false,
      },
      // 设置钱包支付密码路由
      payUrl: {
        type: String,
        default: '/pages/modify/paypwd',
      },
      // 钱包描述是否显示
      descriptionShow: {
        type: Boolean,
        default: true,
      },
      // 支付金额
      money: {
        type: [Number, String],
        default: 0.0,
      },
      // 余额
      balance: {
        type: Number,
        default: 0,
      },
      // 我的钱包余额
      walletBalance: {
        type: Number,
        default: 0,
      },
      // 支付主题类型
      payType: {
        type: String,
        default: '获得权限',
      },
      // 支付于用户name
      toName: {
        type: String,
        default: '',
      },
      // 默认支付方式
      currentPayType: {
        type: [Number, String],
        default: '',
      },
      // 支付提示
      payTipShow: {
        type: Boolean,
        default: true,
      },
      // 支付方式数组
      payTypeData: {
        type: Array,
        default: () => {
          return [];
        },
      },
      // 支付密码
      payPassword: {
        type: String,
        default: '',
      },
      payId: {
        type: [String, Number],
        default: '',
      },
    },

    data() {
      return {
        password: '',
        trantision: false,
        show: false, // 输入支付密码是否显示
        payImmediatelyClick: false,
        checkVal: '1',
        checkStatus: true, // 单选框状态
        // checkStatusVal: 1, // 单选框状态
        current: this.currentPayType,
      };
    },
    computed: {
      p() {
        return this.i18n.t('pay');
      },
    },
    watch: {
      payPassword(val) {
        this.show = val;
        this.descriptionShow = parseFloat(this.money) > parseFloat(this.balance);
        if (!val) {
          this.show = false;
        }
      },
    },
    onLoad() {

    },

    methods: {
      ...mapMutations({
        setRouter: 'pay/SET_ROUTER',
      }),
      // 是否选中显示头像
      radioMyHead(evt) {
        this.checkStatus = !this.checkStatus;
        // this.checkStatusVal = 1 ? 0 : 1;
        if (evt.target.value.length <= 0) {
          this.checkStatusVal = 1;
        } else {
          this.checkStatusVal = 0;
        }
        this.$emit('radioMyHead', this.checkStatus);
      },
      // 父组件触发是否显示弹框
      payClickShow(val) {
        if (val === 0 || val === 2) {
          this.$refs.payPopup.open();
        } else {
          this.$refs.payTypePopup.open();
        }
      },
      // 是否显示钱包密码支付框
      async paysureShow() {
        let self = this;
        if (this.current === 0) {
          // 这是我的钱包（商城）支付
          if (this.money > this.walletBalance) {
            return false;
          }
          // 去商城转账

          let order_no = Math.floor(Math.random() * 1000);
          order_no = new Date().getTime() + order_no;
          this._post('iot.balancebbs/paybbs', {
            pay_price: self.money,
            order_no: order_no,
          }, function(result) {
            let userid = self.$store.getters['session/get']('userId')
            let params = {
              _jv: {
                type: `wallet/user/${userid}`,
              },
              user_id: userid,
              operate_type: 1,
              operate_amount: self.money,
              operate_reason: 'shop',
              wallet_status: 0
            };

            self.$store
              .dispatch('jv/patch', params)
              .then(res => {
                console.log('wallet/user', res);
                self.show = true;
                self.current = 1;
                self.$refs.payTypePopup.close();
                self.$refs.keyboardPopup.open();

                self.$emit('paysureShow', self.current);
                self.current = false; // 将选中的支付方式清除
              }).catch(err => {
                console.log('error', err)
                self._post('iot.balancebbs/paybbs', {
                  pay_price: self.money * -1,
                  order_no: order_no,
                }, function(result) {});
              });
          })
        } else if (this.current === 1) {
          if (this.money > this.balance) {
            return false;
          }
          // 这是钱包支付
          this.show = true;
          this.$refs.payTypePopup.close();
          this.$refs.keyboardPopup.open();
          const that = this;
          that.$emit('paysureShow', this.current);
          that.current = false; // 将选中的支付方式清除
        } else {
          uni.showToast({
            title: this.p.pleaseSelectPaymentMethod,
            icon: 'none',
          });
          const that = this;
          that.$emit('paysureShow', this.current);
          that.current = false; // 将选中的支付方式清除
        }


      },
      // 支付方式单选框change事件
      radioChange(evt) {

        for (let i = 0; i < this.payTypeData.length; i += 1) {
          if (this.payTypeData[i].value === evt.target.value) {
            this.current = i;
            break;
          }
        }
        this.$emit('radioChange', evt.target.value);
      },
      // 确认支付，选择支付方式
      payChoice() {
        this.$refs.payPopup.close();
        this.$refs.payTypePopup.open();
      },
      // 取消支付
      cancel(type) {
        if (type === '1') {
          this.$refs.payPopup.close();
        } else {
          this.$refs.payTypePopup.close();
        }
        this.current = false; // 点击取消后清除已选支付选项
      },
      // 去设置钱包支付密码
      payStatusClick() {
        // /* 获取当前路由 */
        const routes = getCurrentPages(); // 获取当前打开过的页面路由数组
        const curRoute = routes[routes.length - 1].route; // 获取当前页面路由，也就是最后一个打开的页面路由
        this.setRouter(`${curRoute}/${this.threadId}`);
        // this.$store.commit('setRouter', curRoute);
        if (this.payUrl) {
          uni.navigateTo({
            url: this.payUrl
          });
        } else {
          uni.navigateTo({
            url: '/pages/modify/paypwd'
          });
        }

      },
      // 输入密码完成
      onInput(val) {
        // 当输入密码为6位数时
        this.$emit('onInput', val);
      },
      // 关闭密码输入框
      close() {
        this.show = false;
        this.$refs.keyboardPopup.close();
        this.$emit('close');
      },
      // 清空密码输入框
      clearPassword() {
        this.$refs.keyboard.clear();
      },

    },
  };
</script>
<style lang="scss">
  @import '@/styles/base/variable/global.scss';
  @import '@/styles/base/theme/fn.scss';

  .popup-pay {
    display: flex;
    flex-direction: column;
    background: --color(--qui-BG-2);
  }

  .popup-content-space {
    width: 100%;
    height: 9rpx;
    background: --color(--qui-FC-DDD);
  }

  .popup-cancel-btn {
    height: 100rpx;
    font-size: $fg-f4;
    line-height: 90rpx;
    color: #666;
    text-align: center;
    border-top-color: #f5f5f5;
    border-top-style: solid;
    border-top-width: 1px;
  }

  .popup-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .pay-title {
    padding-top: 40rpx;
    padding-bottom: 20rpx;
    font-size: $fg-f4;
    line-height: 37rpx;
    text-align: center;
  }

  .pay-btn {
    display: flex;
    flex-direction: row;
    justify-content: center;
    width: 465rpx;
    height: 90rpx;
    font-size: $fg-f4;
    line-height: 90rpx;
    color: #fff;
    text-align: center;
    background: --color(--qui-RED);

    .pay-num {
      padding: 0 20rpx;
      font-size: 40rpx;
      color: --color(--qui-FC-FFF);
    }
  }

  .pay-radio {
    display: flex;
    flex-direction: row;
    justify-content: center;
    padding: 20rpx 0 40rpx;

    .radio {
      transform: scale(0.7);
    }
  }

  .radio-word {
    font-size: 24rpx;
    line-height: 48rpx;
  }

  .popup-pay-type {
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: --color(--qui-BG-2);
  }

  .money-box {
    display: flex;
    flex-direction: row;
    justify-content: center;
    font-size: 40rpx;
    line-height: 80rpx;

    .money-num {
      font-size: 60rpx;
      line-height: 80rpx;
    }
  }

  .pay-type-chi {
    // display: flex;
    // flex-direction: row;
    // justify-content: space-between;
    height: 99rpx;
    padding: 0 40rpx;
    align-items: center;
    box-sizing: border-box;
  }

  .pay-type-radio {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .radio {
      transform: scale(0.7);
    }
  }

  .pay-type-l {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    .pay-type-word {
      font-size: $fg-f4;
    }
  }

  .pay-type-r {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
  }

  .icon-pay {
    display: flex;
    margin-right: 20rpx;
    font-size: 60rpx;
    line-height: 80rpx;
  }

  .wxpay {
    color: #09bb07;
  }

  .walletpay {
    color: #1878f3;
  }

  .pay-tip {
    padding: 40rpx 0;
    font-size: $fg-f2;
    color: --color(--qui-FC-AAA);
    text-align: center;
  }

  .check-tip {
    padding-right: 20rpx;
    font-size: $fg-f2;
    color: --color(--qui-FC-AAA);
  }

  .pay-radio-box {
    height: 99rpx;
  }

  .popup-share-content-space {
    width: 100%;
    height: 9rpx;
    background: --color(--qui-FC-DDD);
  }

  .paySureBtn {
    width: 100%;
    height: 100rpx;
    font-size: $fg-f4;
    font-weight: normal;
    line-height: 100rpx;
    color: --color(--qui-FC-FFF);
    text-align: center;
    background: --color(--qui-MAIN);
    border-radius: 0;
  }
</style>
